import 'dart:async';
import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_project/common/route_page/route_name.dart';
import 'package:flutter_project/config/common_string_config.dart';
import 'package:flutter_project/config/loading_toast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../../config/theme_color.dart';
import '../../common/privacy/dialog_common_view.dart';
import '../../config/web_page.dart';
import '../../generated/l10n.dart';
import '../../home/app_main_page.dart';
import '../../requst/dio_http_utils.dart';
import 'agree_privacy_login_view.dart';

class UserLoginView extends StatefulWidget {
  const UserLoginView({super.key});

  @override
  State<UserLoginView> createState() => _UserLoginViewState();
}

class _UserLoginViewState extends State<UserLoginView> {
  final TextEditingController _telController = TextEditingController();
  final FocusNode telFocusNode = FocusNode();
  final TextEditingController codeController = TextEditingController();
  final FocusNode codeFocusNode = FocusNode();
  double textSize = 12.0;
  final ValueNotifier<bool> isChose = ValueNotifier<bool>(false);
  final ValueNotifier<int> phoneInputLength = ValueNotifier<int>(0); //监听手机号长度
  final ValueNotifier<bool> isEyes = ValueNotifier<bool>(true);
  final ValueNotifier<bool> isCodeLogin = ValueNotifier<bool>(false); //是否是密码登录
  final ValueNotifier<String> verifyCodeSTtr =
      ValueNotifier<String>('获取验证码'); //是否是密码登录
  Timer? verifyTimer;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        cancelKeyBoard();
      },
      child: Container(
        color: Colors.white,
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              const SizedBox(
                height: 150,
              ),
              Image.asset(
                'assets/images/ic_launcher.png',
                width: 70,
              ),
              const SizedBox(
                height: 20,
              ),
              Text(
                S.of(context).appTitle,
                style:
                    const TextStyle(fontSize: 15, fontWeight: FontWeight.w500),
              ),
              const SizedBox(
                height: 60,
              ),
              Container(
                margin: const EdgeInsets.symmetric(horizontal: 35),
                alignment: Alignment.center,
                height: 45,
                decoration: BoxDecoration(
                    color: ThemeColor.mainBgColor,
                    borderRadius: BorderRadius.circular(25)),
                child: TextField(
                  focusNode: telFocusNode,
                  controller: _telController,
                  keyboardType: TextInputType.phone,
                  style: const TextStyle(
                    fontSize: 14,
                    color: Colors.black,
                  ),
                  onChanged: (res) {
                    phoneInputLength.value = res.length;
                  },
                  decoration: InputDecoration(
                    hintText: "请输入手机号",
                    hintStyle: TextStyle(
                        fontSize: 14, color: ThemeColor.textColorSecond),
                    border: InputBorder.none,
                    contentPadding: const EdgeInsets.only(left: 20),
                  ),
                ),
              ),
              const SizedBox(
                height: 20,
              ),
              ValueListenableBuilder(
                  valueListenable: isCodeLogin,
                  builder: (BuildContext context, bool value, Widget? child) {
                    return Visibility(
                      visible: isCodeLogin.value,
                      child: Container(
                        margin: const EdgeInsets.symmetric(horizontal: 35),
                        alignment: Alignment.center,
                        height: 45,
                        decoration: BoxDecoration(
                            color: ThemeColor.mainBgColor,
                            borderRadius: BorderRadius.circular(25)),
                        child: ValueListenableBuilder(
                            valueListenable: isEyes,
                            builder: (BuildContext context, bool isOpen,
                                Widget? child) {
                              return TextField(
                                obscureText: isEyes.value,
                                focusNode: codeFocusNode,
                                controller: codeController,
                                keyboardType: TextInputType.phone,
                                style: const TextStyle(
                                  fontSize: 14,
                                  color: Colors.black,
                                ),
                                onChanged: (res) {},
                                decoration: InputDecoration(
                                    hintText: "请输入密码",
                                    hintStyle: TextStyle(
                                        fontSize: 14,
                                        color: ThemeColor.textColorSecond),
                                    border: InputBorder.none,
                                    contentPadding: const EdgeInsets.only(
                                        left: 20, top: 10),
                                    suffixIcon: IconButton(
                                        onPressed: () {
                                          isEyes.value = !isEyes.value;
                                        },
                                        icon: Icon(
                                          isEyes.value
                                              ? Icons.visibility_off_outlined
                                              : Icons.visibility,
                                          color: ThemeColor.textColorSecond,
                                        ))),
                              );
                            }),
                      ),
                    );
                  }),
              ValueListenableBuilder(
                  valueListenable: isCodeLogin,
                  builder: (BuildContext context, bool value, Widget? child) {
                    return Offstage(
                      offstage: isCodeLogin.value,
                      child: Container(
                        margin: const EdgeInsets.symmetric(horizontal: 35),
                        alignment: Alignment.center,
                        height: 45,
                        decoration: BoxDecoration(
                            color: ThemeColor.mainBgColor,
                            borderRadius: BorderRadius.circular(25)),
                        child: Row(
                          children: [
                            Expanded(
                              child: TextField(
                                focusNode: codeFocusNode,
                                controller: codeController,
                                keyboardType: TextInputType.phone,
                                style: const TextStyle(
                                  fontSize: 14,
                                  color: Colors.black,
                                ),
                                onChanged: (res) {},
                                decoration: InputDecoration(
                                  hintText: "请输入验证码",
                                  hintStyle: TextStyle(
                                      fontSize: 14,
                                      color: ThemeColor.textColorSecond),
                                  border: InputBorder.none,
                                  contentPadding: const EdgeInsets.only(
                                    left: 20,
                                  ),
                                ),
                              ),
                            ),
                            TextButton(
                                onPressed: () {
                                  getVerifyCode();
                                },
                                child: ValueListenableBuilder(
                                    valueListenable: verifyCodeSTtr,
                                    builder: (BuildContext context,
                                        String value, Widget? child) {
                                      return Text(value);
                                    })),
                          ],
                        ),
                      ),
                    );
                  }),
              const SizedBox(
                height: 36,
              ),
              Text('如未注册会自动注册并登录',style: TextStyle(color: ThemeColor.textColorSecond,fontSize: 14),),
              const SizedBox(
                height: 16,
              ),
              ValueListenableBuilder(
                valueListenable: phoneInputLength,
                builder: (BuildContext context, int value, Widget? child) {
                  return GestureDetector(
                    onTap: () {
                      String code = codeController.text;
                      String phone = _telController.text;
                      if (phone.isEmpty) {
                        toast('请输入手机号');
                        return;
                      }
                      if (phone.length != 11) {
                        toast('请输入正确手机号');
                        return;
                      }
                      if (code.isEmpty) {
                        toast('请输入验证码');
                        return;
                      }
                      cancelKeyBoard();
                      if (isChose.value == false) {
                        ConfirmAlertDialog.showPrivacyDialog(context,
                            childWidget: AgreePrivacyLoginView(
                          agreeAction: () {
                            isChose.value = true;
                            loginAction(codeStr: code, phoneStr: phone);
                          },
                        ));
                        return;
                      }
                      loginAction(codeStr: code, phoneStr: phone);
                    },
                    child: Container(
                      margin: const EdgeInsets.symmetric(horizontal: 35),
                      alignment: Alignment.center,
                      height: 45,
                      decoration: BoxDecoration(
                          color: (phoneInputLength.value > 0)
                              ? ThemeColor.mainColor
                              : const Color(0x803778FD),
                          borderRadius: BorderRadius.circular(25)),
                      child: const Text(
                        '登录',
                        style: TextStyle(
                            fontSize: 14,
                            color: Colors.white,
                            fontWeight: FontWeight.bold),
                      ),
                    ),
                  );
                },
              ),
              const SizedBox(
                height: 10,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  ValueListenableBuilder(
                      valueListenable: isChose,
                      builder:
                          (BuildContext context, bool value, Widget? child) {
                        String iconStr = value == false
                            ? 'assets/images/ic_agree_uncheck.png'
                            : 'assets/images/ic_agree_check.png';
                        return GestureDetector(
                          onTap: () {
                            isChose.value = !isChose.value;
                          },
                          child: Image.asset(
                            iconStr,
                            width: 18,
                          ),
                        );
                      }),
                  const SizedBox(
                    width: 4,
                  ),
                  RichText(
                      text: TextSpan(
                          text: '我已阅读并同意',
                          recognizer: TapGestureRecognizer()
                            ..onTap = () {
                              isChose.value = !isChose.value;
                            },
                          style: TextStyle(
                              color: ThemeColor.textColorSecond,
                              fontSize: textSize),
                          children: [
                        TextSpan(
                          text: "《用户协议》",
                          style: TextStyle(
                              color: const Color(0xFF7F69D9),
                              fontSize: textSize),
                          recognizer: TapGestureRecognizer()
                            ..onTap = () {
                              jumpAgreeWebPrivacy(
                                  urlStr: 'assets/html/UserPolicy.html',
                                  titleStr: '用户协议');
                            },
                        ),
                        TextSpan(
                          text: "《隐私政策》\n",
                          style: TextStyle(
                              color: const Color(0xFF7F69D9),
                              fontSize: textSize),
                          recognizer: TapGestureRecognizer()
                            ..onTap = () {
                              jumpAgreeWebPrivacy(
                                  urlStr: 'assets/html/PrivacyPolicy.html',
                                  titleStr: '隐私政策');
                            },
                        ),
                        TextSpan(
                          text: "《个人信息收集清单》",
                          style: TextStyle(
                              color: const Color(0xFF7F69D9),
                              fontSize: textSize),
                          recognizer: TapGestureRecognizer()
                            ..onTap = () {
                              jumpAgreeWebPrivacy(
                                  urlStr: 'assets/html/PersonInfoCollect.html',
                                  titleStr: '个人信息收集清单');
                            },
                        ),
                        TextSpan(
                          text: "《申请使用权限》",
                          style: TextStyle(
                              color: const Color(0xFF7F69D9),
                              fontSize: textSize),
                          recognizer: TapGestureRecognizer()
                            ..onTap = () {
                              jumpAgreeWebPrivacy(
                                  urlStr: 'assets/html/ApplyUserRight.html',
                                  titleStr: '申请使用权限');
                            },
                        ),
                      ]))
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

//取消键盘
  cancelKeyBoard() {
    if (telFocusNode.hasFocus) {
      telFocusNode.unfocus();
    }
    if (codeFocusNode.hasFocus) {
      codeFocusNode.unfocus();
    }
  }

  @override
  void dispose() {
    super.dispose();
    cancelTimer();
  }

  //取消定时器
  void cancelTimer() {
    if (verifyTimer != null && verifyTimer!.isActive) {
      verifyTimer!.cancel();
    }
    debugPrint('取消了定时器');
  }

//获取验证码
  void getVerifyCode() {
    int count = 61;
    if (verifyCodeSTtr.value.contains('获取') == false) {
      return;
    }

    String phone = _telController.text;
    if (phone.isEmpty) {
      toast('请输入手机号');
      return;
    }
    if (phone.length != 11) {
      toast('请输入正确手机号');
      return;
    }
    verifyTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (count == 1) {
        cancelTimer();
        verifyCodeSTtr.value = '再次获取';
        return;
      }
      count--;
      verifyCodeSTtr.value = '$count';
    });

    HttpDioUtils.request('account/getPhoneCode',
        params: {'PhoneNumber': phone});
  }

  //登录
  void loginAction({
    String codeStr = '',
    String phoneStr = '',
  }) async {
    bool isAgree = isChose.value;

    Map<String, dynamic>? dataMap = {
      'Code': codeStr,
      'Phone': phoneStr,
      'agree': isAgree
    };
    var res = await HttpDioUtils.request('account/loginPhoneWithCode',
        params: dataMap);

    if (res['ErrCode'] == 0) {
      String token = res['Resp']['Token'];
      SharedPreferences sharedPreferences =
          await SharedPreferences.getInstance();
      sharedPreferences.setString('token', token);
      sharedPreferences.setString('mobile', phoneStr);
      CommonStringConfig.loginToken = token;
      RouteNames.pushReplacement(const AppMainPage());
    }
  }

  //跳转隐私协议
  void jumpAgreeWebPrivacy({required String urlStr, required String titleStr}) {
    cancelKeyBoard();
    RouteNames.push(
      WebPage(
        url: urlStr,
        title: titleStr,
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    getLocalToken();
    getDeviceInfo();
  }

  getLocalToken() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String? token = sharedPreferences.getString('token');
    if (token != null && token.isNotEmpty) {
      CommonStringConfig.loginToken = token;
    }
    String? mobile = sharedPreferences.getString('mobile');
    if (mobile != null && mobile.isNotEmpty) {
      _telController.text = mobile;
    }
  }

  getDeviceInfo() async {
    DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
    final deviceInfo = await deviceInfoPlugin.deviceInfo;
    final allInfo = deviceInfo.data;
    CommonStringConfig.uuid =
        Platform.isIOS ? allInfo['name'] : allInfo['model'];
    debugPrint('设备uuid${CommonStringConfig.uuid}');
  }
}
